package com.nxj.config;

import com.nxj.pojo.Configuration;
import com.nxj.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public MappedStatement parseMapper(InputStream inputStream) throws Exception {
        Document document = new SAXReader().read(inputStream);
        Element rootEle = document.getRootElement();

        String namespace = String.valueOf(rootEle.attributeValue("namespace"));
        doIteratorMap(namespace, rootEle.selectNodes("//select"));
        doIteratorMap(namespace, rootEle.selectNodes("//insert"));
        doIteratorMap(namespace, rootEle.selectNodes("//update"));
        doIteratorMap(namespace, rootEle.selectNodes("//delete"));
        return null;
    }

    public void doIteratorMap(String namespace, List<Element> elements) throws Exception {
        if (elements == null || elements.size() < 1) {
            return;
        }
        for (Element e : elements) {
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(e.attributeValue("id"));
            mappedStatement.setSql(e.getTextTrim());
            if (e.attributeValue("resultType") != null) {
                mappedStatement.setResultType(Class.forName(e.attributeValue("resultType")));
            }
            if (e.attributeValue("paramterType") != null) {
                mappedStatement.setParamterType(Class.forName(e.attributeValue("paramterType")));
            }
            configuration.getMappedStatementMap().put(namespace + "." + mappedStatement.getId(), mappedStatement);
        }
    }


}
